package org.phalanx.gwt.client.shared;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;

public class AuthenticationManager implements RequestCallback {
	private AuthenticationListener authListen;
	private boolean tokenLogin = false;
	
	public AuthenticationManager(AuthenticationListener a){
		authListen = a;
	}
	
	public void sendLoginRequest(String username, String password){
		tokenLogin = username.isEmpty() && password.isEmpty() ? true : false;
		String postString = "context=authentication&username=" + username + "&password=" + password + "&";
		RequestBuilder loginPOST = new RequestBuilder(RequestBuilder.POST, "/PhalanxServlet/ServerInstance");

		try {
			loginPOST.setHeader("Content-Type", "application/x-www-form-urlencoded");
			loginPOST.sendRequest(postString, this);
		} catch (RequestException e) {
			authListen.authCallBack(false, AuthenticationListener.SERVER_DOWN);
		}
	}
	
	public void sendLoginRequest(){
		// Sends a blank username and password which just checks if
		// a cookie token is already validated on the server
		sendLoginRequest("", "");
	}
	
	@Override
	public void onError(Request request, Throwable exception) {
		authListen.authCallBack(false, AuthenticationListener.SERVER_DOWN);
	}

	@Override
	public void onResponseReceived(Request request, Response response) {
		if (response.getText().equalsIgnoreCase("Authentication Success")){
			authListen.authCallBack(true, tokenLogin ? AuthenticationListener.AUTH_SUCCESS_TOKEN : AuthenticationListener.AUTH_SUCCESS_FIRST_LOGIN);
		}
		else {
			authListen.authCallBack(false, AuthenticationListener.AUTH_FAILED);
		}

	}

}
